package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Method;

/**
 * @Classname: Test5
 * @Author: bromide
 * @CreateTime: 2022/4/19--15:06
 * @Version: V1.0
 * @Description: 自动调用与Test4在同一个包中那些被@AutoRunClass标注的类中所有被@AutoRunMethod标注的方法
 * n次，n对应的是注解@AutoRunMethod传入的参数值
 */
public class Test5 {
    public static void main(String[] args) throws Exception {
        File dir = new File(Test4.class.getResource(".").toURI());
        File[] files = dir.listFiles(file -> file.getName().endsWith(".class"));
        String pathName = Test4.class.getPackage().getName();
        for (File file : files) {
            String fileName = file.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName(pathName + "." + className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();
                        System.out.println("自动调用" + className + "中的" + method.getName() + "方法" + value + "次");
                        for (int i = 0; i < value; i++) {
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
